import '@umijs/max';
import { Button, Col, Flex, Image, message, Row, Space, Spin, Typography } from 'antd';
import React, { useState } from 'react';
import {
  createPictureOutPaintingTaskUsingPost,
  getPictureOutPaintingTaskUsingGet,
} from '@/services/backend/pictureController';
import {uploadPictureByUrlUsingPost} from "@/services/backend/fileController";

interface Props {
  data: API.PictureVO;
  onFinish?: () => void;
}

/**
 * 创建弹窗
 * @param props
 * @constructor
 */
const AIOutPainting: React.FC<Props> = (props) => {
  const { data,onFinish } = props;
  const [aiOutPaintingLoading, setAIOutPaintingLoading] = useState<boolean>(false);
  const [aiOutPaintingURL, setAIOutPaintingURL] = useState<string | undefined>(undefined);
  // const [currentTaskId, setCurrentTaskId] = useState<string>('');
  let currentTaskId: any = '';
  // 轮询定时器
  //@ts-ignore
  let pollingTimer: NodeJS.Timer = null;

  // 清理轮询定时器
  const clearPolling = () => {
    if (pollingTimer) {
      clearInterval(pollingTimer);
      pollingTimer = null;
      currentTaskId = '';
    }
  };

  // 开始轮询
  const startPolling = () => {
    setAIOutPaintingLoading(true);
    pollingTimer = setInterval(async () => {
      console.log('polling');
      try {
        const res = await getPictureOutPaintingTaskUsingGet({
          taskId: currentTaskId,
        });
        console.log('轮询任务状态', res);
        if (res.code === 0 && res.data) {
          const taskResult = res.data.output;
          if (!taskResult) {
            return;
          }
          if (taskResult.taskStatus === 'SUCCEEDED') {
            message.success('扩图任务成功');
            console.log(taskResult?.outputImageUrl);
            setAIOutPaintingURL(taskResult?.outputImageUrl);
            clearPolling();
            setAIOutPaintingLoading(false);
          } else if (taskResult.taskStatus === 'FAILED') {
            message.error('扩图任务失败');
            clearPolling();
            setAIOutPaintingLoading(false);
          }
        }
      } catch (error) {
        console.error('轮询任务状态失败', error);
        message.error('检测任务状态失败，请稍后重试');
        clearPolling();
        setAIOutPaintingLoading(false);
      }
    }, 1000); // 每隔 3 秒轮询一次
  };
  /**
   * 创建任务
   */
  const createTask = async () => {
    setAIOutPaintingURL(undefined);
    if (!data.id) {
      return;
    }
    const res = await createPictureOutPaintingTaskUsingPost({
      pictureId: data.id,
      // 可以根据需要设置扩图参数
      parameters: {
        xScale: 2,
        yScale: 2,
      },
    });
    console.log(res.data);
    if (res.code === 0 && res.data) {
      console.log(res.data.output.taskId);
      currentTaskId = res.data.output.taskId;
      startPolling();
    } else {
      message.error('创建任务失败，' + res.message);
    }
  };
  const applyPicture = async () => {
    if (!aiOutPaintingURL) {
      message.error('图片链接不能为空');
    }
    try {
      await uploadPictureByUrlUsingPost({
        id: data.id,
        fileUrl: aiOutPaintingURL,
      });
      message.success('应用成功');
    } catch (e: any) {
      message.error('应用失败:' + e.getMessage());
    }finally {
      onFinish?.();
    }
  };
  return (
    <>
      <Row gutter={24}>
        <Col span={12}>
          <Typography.Title level={5}>原图</Typography.Title>
          <Image src={data.url}></Image>
        </Col>
        <Col span={12}>
          <Typography.Title level={5}>AI扩图</Typography.Title>
          {aiOutPaintingURL && <Image src={aiOutPaintingURL}></Image>}
          {aiOutPaintingLoading && <Spin />}
        </Col>
      </Row>
      <Flex justify={'center'} style={{ marginTop: 24 }}>
        <Space>
          <Button
            onClick={async () => {
              await createTask();
            }}
          >
            生成图片
          </Button>
          <Button type={'primary'} onClick={applyPicture}>应用此图</Button>
        </Space>
      </Flex>
    </>
  );
};
export default AIOutPainting;
